package com.shrio;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.encoder.QRCode;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

import static com.google.zxing.client.j2se.MatrixToImageConfig.BLACK;
import static com.google.zxing.client.j2se.MatrixToImageConfig.WHITE;

public class QrCodeUtil {

    public static void main(String[] args) {
         QRCode test = new QRCode();
//         File file1 = new File("D:/测试");
//         if(!file1.exists()){
//             file1.mkdir();
//         }
         File file = new File("D:/test.png");
//         if(!file.exists()){
             Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
             hints.put(EncodeHintType.MARGIN, 0);  //设置白边
             String content = "15708464216";
             encode(content, file, BarcodeFormat.QR_CODE, 182, 182, hints);
             System.out.println("---------encode success---------");
//         }else {
//             decode(file);
//             System.out.println("---------decode success---------");
//         }


    }
    public static void encode(String contents, File file, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) {
         try {
            //消除乱码
            contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
                 BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height, hints);
                 //去百边
//                 bitMatrix = deleteWhite(bitMatrix);
                 writeToFile(bitMatrix, "png", file);
             } catch (Exception e) {
                 e.printStackTrace();
             }
    }

    public static BitMatrix deleteWhite(BitMatrix matrix){
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
         BufferedImage image = toBufferedImage(matrix);
         ImageIO.write(image, format, file);
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
         int width = matrix.getWidth();
         int height = matrix.getHeight();
         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
         for (int x = 0; x < width; x++) {
             for (int y = 0; y < height; y++) {
                 image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
             }
         }
         return image;
    }

    /**
           * 解析QRCode二维码
           */
     @SuppressWarnings("unchecked")
     public static void decode(File file) {
                 try {
                         BufferedImage image;
                         try {
                                 image = ImageIO.read(file);
                                 if (image == null) {
                                         System.out.println("Could not decode image");
                                     }
                                 LuminanceSource source = new BufferedImageLuminanceSource(image);
                                 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                                 Result result;
                                 @SuppressWarnings("rawtypes")
                                 Hashtable hints = new Hashtable();
                                 //解码设置编码方式为：utf-8
                                 hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
                                 result = new MultiFormatReader().decode(bitmap, hints);
                                 String resultStr = result.getText();
                                 System.out.println("解析后内容：" + resultStr);
                             } catch (IOException ioe) {
                                 System.out.println(ioe.toString());
                             } catch (ReaderException re) {
                                 System.out.println(re.toString());
                             }
                     } catch (Exception ex) {
                         System.out.println(ex.toString());
                     }
             }
}
